<template>
  <div class="chart" ref="chartRef"></div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import * as echarts from 'echarts'
import http from '../http.js'

const chartRef = ref<HTMLElement | null>(null)

onMounted(() => {
  // 1. 获取地图数据
  fetch('https://geo.datav.aliyun.com/areas_v3/bound/100000_full.json')
    .then(res => res.json())
    .then(async (geoJson) => {
      echarts.registerMap('china', geoJson)

      // 2. 请求业务数据
      const res = await http.get('/map.json')
      // 3. 组装 legend 和 series
      const legendData = res.map((item: any) => item.name)
      const series = res.map((item: any) => ({
        name: item.name,
        type: 'effectScatter',
        coordinateSystem: 'geo',
        data: item.children.map((c: any) => ({
          name: c.name,
          value: c.value
        })),
        symbolSize: 12,
        itemStyle: {
          color:
            item.name === '黄金用户'
              ? '#7cffb2'
              : item.name === '白金用户'
              ? '#58c8ff'
              : '#4992ff'
        }
      }))

      // 4. 组装 option
      const option = {
        title: {
          text: '| 商家分布',
          textStyle: {
            color: '#fff',
            fontSize: 14,
            fontWeight: 'normal'
          },
          left: '2%',
          top: '2%'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{b}'
        },
        legend: {
          orient: 'vertical',
          left: '2%',
          bottom: '6%',
          textStyle: {
            color: '#fff'
          },
          data: legendData
        },
        geo: {
          map: 'china',
          roam: true,
          zoom: 1.2,
          center: [105, 35],
          label: { show: false },
          itemStyle: {
            areaColor: '#142957',
            borderColor: '#404a59',
            borderWidth: 1
          },
          emphasis: {
            itemStyle: {
              areaColor: '#2a333d'
            }
          },
          regions: [{
            name: '新疆',
            itemStyle: {
              areaColor: '#fddd60'
            }
          }]
        },
        series
      }

      // 5. 渲染图表
      const myChart = echarts.init(chartRef.value!)
      myChart.setOption(option)
      window.addEventListener('resize', () => myChart.resize())
    })
})
</script>

<style scoped>
.chart {
  width: 100%;
  height: 100%;
  padding: 10px;
}
</style>
